package com.lagou.consumer;

import com.lagou.entity.COrder;
import com.lagou.repository.COrderRepository;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Optional;

/**
 * @author mcl
 * @date 2021/10/4 14:10
 * @description
 */
@Component
public class OrderConsumer {

    @Autowired
    private COrderRepository cOrderRepository;

    @RabbitListener(queues = "q.go.dlx", ackMode = "MANUAL")
    public void service(Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, @Payload String message) throws IOException {

        Optional<COrder> order = cOrderRepository.findById(Long.valueOf(message));
        if (order.isPresent()) {
            COrder cOrder = order.get();
            if ("Paying".equals(cOrder.getStatus())) {
                System.out.println("超时订单: " + message);
                cOrder.setStatus("TimeOut");
                cOrderRepository.saveAndFlush(cOrder);
            } else {
                System.out.println("订单: " + message + "已支付");
            }
        }
        channel.basicAck(deliveryTag, false);
    }
}
